package com.hp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hp.entity.User;
import com.hp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: Admin
 * @Date: 2021/10/22 22:04
 */
@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询users用户信息
     * @param page 页码
     * @param model
     * @return
     */
    @GetMapping("/userList")
    public String userList(int page, Model model){
        //userList 查询全部用户信息，返回数据
        PageHelper.startPage(page,5);

        List<User> userList = userService.userList();

        PageInfo pageInfo = new PageInfo(userList);
        model.addAttribute("userList",userList);
        model.addAttribute("pageInfo",pageInfo);
        return "admins/user_list";
    }

    /**
     * 根据id删除信息
     * @param id
     * @return
     */
    @GetMapping("/userDelete")
    public String userDelete(@RequestParam("id") Integer id){
        userService.findUserByIdDelete(id);
        return "redirect:/admin/userList?page=1";
    }

    /**
     * 跳转修改页面
     * @param id 根据id查询信息
     * @param model
     * @return
     */
    @GetMapping("/userEdit")
    public String userEdit(@RequestParam("id") Integer id, Model model){
        //user 根据id查询users信息
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "admins/user_edit";
    }

    /**
     * 修改数据
     * @param user
     * @return
     */
    @PostMapping("/userUpdate")
    public String userUpdate(User user){
        userService.userUpdate(user);
        return "redirect:/admin/userList?page=1";
    }

    /**
     * 跳转新增页面
     * @return
     */
    @GetMapping("/toUserAdd")
    public String toUserAdd(){
        return "admins/user_add";
    }

    /**
     * 新增信息
     * @param user
     * @return
     */
    @PostMapping("/userSave")
    public String userSave(User user){
        userService.userSave(user);
        return "redirect:/admin/userList?page=1";
    }

    @GetMapping("/toUserReset")
    public String toUserReset(@RequestParam("id") Integer id,Model model){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "admins/user_reset";
    }

    @PostMapping("/userReset")
    public String userReset(User user){
        userService.userReset(user);
        return "redirect:/admin/userList?page=1";
    }
}
